<?php

namespace app\controller;

use app\facade\SheetXlsx;
use app\model\Filedata;
use think\facade\Db;
use think\facade\Filesystem;

class FiledataController
{
    protected $middleware = ['AuthCheck'];

    //获取所有文件资料
    public function getFileData()
    {
        return rejson(1, ['filedatas' => Filedata::select()]);
    }

    //导入xlsx文件数据
    public function FileData()
    {
        //验证是否上传文件
        if (!request()->has('fileSheet', 'file')) {
            return rejson(0, null, '请上传文件', 412);
        }
        //获取文件并保存
        $fileSheet = request()->file('fileSheet');
        $savePath = 'file/' . date('Y-m-d', time());
        $fileSheetName = Filesystem::disk('excel')->putFile($savePath, $fileSheet, function () {
            return date('YmdHis', time());
        });
        $fileSheetPath = app()->getRootPath() . 'storage/excel/' . $fileSheetName;
        //解析文件数据
        $sheetDatas = SheetXlsx::get($fileSheetPath, 'A', 'F');
        array_shift($sheetDatas);
        Db::startTrans();
        try {
            $saveDatas = [];
            foreach ($sheetDatas as $data) {
                $saveDatas[] = [
                    'name' => $data['A'],
                    'status' => $data['B'],
                    'source' => $data['C'],
                    'cycle' => $data['D'],
                    'group_leader' => $data['E'],
                    'stalker' => $data['F']
                ];
            }
            $Filedata = new Filedata();
            $filedatas = $Filedata->saveAll($saveDatas);
            Db::commit();
        } catch (\Exception $e) {
            unlink($fileSheetPath);
            //回滚事务
            Db::rollback();
            return rejson(0, null, '数据添加失败,请重试', 500);
        }
        return rejson(1, ['filedatas' => $filedatas]);
    }

    //上传资料文件
    public function importFile()
    {
        $id = input('post.id');
        $dataType = input('post.dataType');
        if (!request()->has('fileData', 'file')) {
            return rejson(0, null, '请上传文件', 412);
        }
        $fileData = request()->file('fileData');
        $fileName = $dataType . '_' . date('YmdHis', time()) . '.' . $fileData->getOriginalExtension();
        $fileDataName = Filesystem::disk('public')->putFileAs('fileData/' . date('Y-m-d', time()), $fileData, $fileName);
        $fileDataPath = 'storage/' . $fileDataName;
        $fileDatas = Filedata::update([
            $dataType => $fileDataPath,
            'id' => $id
        ]);
        return rejson(1, ['filePath' => $fileDatas->$dataType]);
    }
}

